//
//  DataPickerViewController.swift
//  bill
//
//  Created by RongJI on 2021/1/13.
//

import UIKit


enum DatePickerPresentAnimateType {
    case present//被推出时
    case dismiss//取消时
}

//EWDatePickerViewController的推出和取消动画
class DatePickerPresentAnimated: NSObject,UIViewControllerAnimatedTransitioning {
    
    var type: DatePickerPresentAnimateType = .present
    
    init(type: DatePickerPresentAnimateType) {
        self.type = type
    }
    /// 动画时间
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.3
    }
    /// 动画效果
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        switch type {
        case .present:
            guard let toVC = transitionContext.viewController(forKey: .to) as? DataPickerViewController else {
                return
            }
            //            let toVC : EWDatePickerViewController = transitionContext.viewController(forKey: .to) as? EWDatePickerViewController
            let toView = toVC.view
            
            let containerView = transitionContext.containerView
            containerView.addSubview(toView!)
            
            toVC.containV.transform = CGAffineTransform(translationX: 0, y: (toVC.containV.frame.height))
            
            UIView.animate(withDuration: 0.25, animations: {
                /// 背景变色
                toVC.backgroundView.alpha = 1.0
                /// datepicker向上推出
                toVC.containV.transform =  CGAffineTransform(translationX: 0, y: -10)
            }) { ( _ ) in
                UIView.animate(withDuration: 0.2, animations: {
                    /// transform初始化
                    toVC.containV.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    transitionContext.completeTransition(true)
                })
            }
        case .dismiss:
            guard let toVC = transitionContext.viewController(forKey: .from) as? DataPickerViewController else {
                return
            }
            UIView.animate(withDuration: 0.25, animations: {
                toVC.backgroundView.alpha = 0.0
                /// datepicker向下推回
                toVC.containV.transform =  CGAffineTransform(translationX: 0, y: (toVC.containV.frame.height))
            }) { (_) in
                transitionContext.completeTransition(true)
            }
        }
    }
}

enum DatePickerType {
    case year
    case month
    case day
}

class DataPickerViewController: UIViewController {
    
    var backDate: ((String) -> Void)?
    var type : DatePickerType?
    ///获取当前日期
    private var currentDateCom: DateComponents = Calendar.current.dateComponents([.year, .month, .day],   from: Date())    //日期类型
    var containV:UIView = {
        let view = UIView(frame: CGRect(x: 0, y: ScreenInfo.Height-240, width: ScreenInfo.Width, height: 240))
        return view
    }()
    
    var backgroundView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
        return view
    }()
    
    var picker: UIPickerView = {
        let picker = UIPickerView(frame: CGRect(x: 0, y: 24, width: ScreenInfo.Width, height: 216))
        return picker
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let sure = UIButton()
        let cancel = UIButton()
        cancel.setTitle("取消", for: .normal)
        sure.setTitle("确认", for: .normal)
        cancel.setTitleColor(UIColor.blue, for: .normal)
        sure.setTitleColor(UIColor.blue, for: .normal)
        cancel.addTarget(self, action: #selector(self.onClickCancel), for: .touchUpInside)
        sure.addTarget(self, action: #selector(self.onClickSure), for: .touchUpInside)
        self.picker.delegate = self
        self.picker.dataSource = self
        self.picker.backgroundColor = UIColor.clear
        self.picker.clipsToBounds = true//如果子视图的范围超出了父视图的边界，那么超出的部分就会被裁剪掉。
        //创建日期选择器
        self.containV.addSubview(cancel)
        self.containV.addSubview(sure)
        self.containV.addSubview(self.picker)
        self.view.addSubview(self.containV)
        
        cancel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(0)
            make.width.equalTo(70)
            make.height.equalTo(30)
        }
        sure.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(0)
            make.width.equalTo(70)
            make.height.equalTo(30)
        }
    }
    // MARK: onClick
    @objc func onClickCancel() {
        self.dismiss(animated: true, completion: nil)
    }
    @objc func onClickSure() {
        var dateString : String
        switch type {
        case .month:
            dateString = String(format: "%02ld-%02ld", self.picker.selectedRow(inComponent: 0) + (self.currentDateCom.year!), self.picker.selectedRow(inComponent: 1) + 1)

        case .year:
            dateString = String(format: "%02ld", self.picker.selectedRow(inComponent: 0) + (self.currentDateCom.year!))
            break
        default:
            dateString = String(format: "%02ld-%02ld-%02ld", self.picker.selectedRow(inComponent: 0) + (self.currentDateCom.year!), self.picker.selectedRow(inComponent: 1) + 1, self.picker.selectedRow(inComponent: 2) + 1)
            break
        }
        
        print(dateString)
        /// 直接回调显示
        if self.backDate != nil {
            self.backDate!(dateString)
        }
        self.dismiss(animated: true, completion: nil)
    }
    ///点击任意位置view消失
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        let currentPoint = touches.first?.location(in: self.view)
        if !self.containV.frame.contains(currentPoint ?? CGPoint()) {
            self.dismiss(animated: true, completion: nil)
        }
    }
}

// MARK: - PickerViewDelegate
extension DataPickerViewController:UIPickerViewDelegate,UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        switch type {
        case .year:
            return 1
        case .month:
            return 2
        default:
            break
        }
        return 3
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return 10
        } else if component == 1 {
            return 12
        } else {
            let year: Int = pickerView.selectedRow(inComponent: 0) + currentDateCom.year!
            let month: Int = pickerView.selectedRow(inComponent: 1) + 1
            let days: Int = howManyDays(inThisYear: year, withMonth: month)
            return days
        }
    }
    private func howManyDays(inThisYear year: Int, withMonth month: Int) -> Int {
        if (month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12) {
            return 31
        }
        if (month == 4) || (month == 6) || (month == 9) || (month == 11) {
            return 30
        }
        if (year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3) {
            return 28
        }
        if year % 400 == 0 {
            return 29
        }
        if year % 100 == 0 {
            return 28
        }
        return 29
    }
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        
        switch type {
        case .year:
            return ScreenInfo.Width
        case .month:
            return ScreenInfo.Width / 2
        default:
            break
        }
        return ScreenInfo.Width / 3
    }
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 40
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            return "\((currentDateCom.year!) + row)\("年")"
        } else if component == 1 {
            return "\(row + 1)\("月")"
        } else {
            return "\(row + 1)\("日")"
        }
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        switch type {
        case .year:
            break
        case .month:
            break
        default:
            if component == 1 {
                pickerView.reloadComponent(2)
            }
            break
        }
    }
}
// MARK: - 转场动画delegate
extension DataPickerViewController :UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animated = DatePickerPresentAnimated(type: .present)
        return animated
    }
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animated = DatePickerPresentAnimated(type: .dismiss)
        return animated
    }
}



class BillTypePickerViewController: UIViewController {
    var typeString : String?
    var typeBack: ((_ string:String) -> Void)?
    
    //日期类型
    var containV:UIView = {
        let view = UIView(frame: CGRect(x: 0, y: ScreenInfo.Height-240, width: ScreenInfo.Width, height: 240))
        return view
    }()
    
    var backgroundView:UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
        return view
    }()
    
    var picker: UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let sure = UIButton()
        let cancel = UIButton()
        cancel.setTitle("取消", for: .normal)
        sure.setTitle("确认", for: .normal)
        cancel.setTitleColor(UIColor.blue, for: .normal)
        sure.setTitleColor(UIColor.blue, for: .normal)
        cancel.addTarget(self, action: #selector(self.onClickCancel), for: .touchUpInside)
        sure.addTarget(self, action: #selector(self.onClickSure), for: .touchUpInside)
        picker = UIPickerView(frame: CGRect(x: 0, y: 24, width: ScreenInfo.Width, height: 216))
        picker.delegate = self
        picker.dataSource = self
        picker.backgroundColor = UIColor.clear
        picker.clipsToBounds = true//如果子视图的范围超出了父视图的边界，那么超出的部分就会被裁剪掉。
        //创建日期选择器
        self.containV.addSubview(cancel)
        self.containV.addSubview(sure)
        self.containV.addSubview(picker)
        self.view.addSubview(self.containV)
        
        cancel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(0)
            make.width.equalTo(70)
            make.height.equalTo(30)
        }
        sure.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(0)
            make.width.equalTo(70)
            make.height.equalTo(30)
        }
    }
    // MARK: onClick
    @objc func onClickCancel() {
        self.dismiss(animated: true, completion: nil)
    }
    @objc func onClickSure() {
        /// 直接回调显示
        if self.typeBack != nil {
            self.typeBack!(BillOperationManager.instance.billTypeArr![self.picker.selectedRow(inComponent: 0)] as! String)
        }
        
        self.dismiss(animated: true, completion: nil)
    }
    ///点击任意位置view消失
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        let currentPoint = touches.first?.location(in: self.view)
        if !self.containV.frame.contains(currentPoint ?? CGPoint()) {
            self.dismiss(animated: true, completion: nil)
        }
    }
}

// MARK: - PickerViewDelegate
extension BillTypePickerViewController:UIPickerViewDelegate,UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        return BillOperationManager.instance.billTypeArr!.count
    }
    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 40
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return BillOperationManager.instance.billTypeArr![row] as? String
    }
    
}
// MARK: - 转场动画delegate
extension BillTypePickerViewController :UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animated = DatePickerPresentAnimated(type: .present)
        return animated
    }
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        let animated = DatePickerPresentAnimated(type: .dismiss)
        return animated
    }
}
